package com.interview.algorithm;

/**
 * Copyright (C), 2018-2020
 * FileName: 爬楼梯
 * Author:   孔繁玉
 * Date:     2020/12/26 下午8:48
 */
public class 爬楼梯 {

    public static void main(String[] args) {

        for (int i = 1; i <= 10; i++) {
            //int count = fun3(i);
            int count = fun4(i,3);
            System.out.println(i + "------" + count);
        }

    }

    /**
     * 动态规划求解f(n,m)
     * @param n
     * @param m
     * @return
     */
    private static int fun4(int n,int m){
        if (n == 1 || n == 2) {  //边界 f(1) = 1,f(2)=2
            return n;
        }

        int[] array = new int[n + 1];
        array[0] = 1;
        array[1] = 1;
        //分两种情况讨论
        //1. n<m, f(n,m)=f(n-1)+f(n-2)+...+f(1)
        //2. n>=m,f(n,m)=f(n-1)+f(n-2)+...+f(n-m)
        for (int i = 2; i <=n ; i++) {
            int max = i < m ? i : m;
            for (int j = 1; j <=max ; j++) {
                array[i] += array[i - j];
            }
        }
        return array[n];
    }


    /**
     * 动态规划法
     * @param n
     * @return
     */
    private static int fun3(int n) {
        if (n == 1 || n == 2) {  //边界 f(1) = 1,f(2)=2
            return n;
        }

        int[] array = new int[n + 1];
        array[0] = 1;//i=2的时候需要前两项相加
        array[1] = 1;
        for (int i = 2; i <= n; i++) {
            array[i] = array[i - 1] + array[i - 2];//状态转移方程
        }
        return array[n];
    }

    /**
     * 循环法
     *
     * @param n
     * @return
     */
    private static int fun2(int n) {
        if (n == 1 || n == 2) {
            return n;
        }
        int first = 1;
        int second = 2;
        int temp = 0;
        for (int i = 3; i <= n; i++) {
            temp = first + second;
            first = second;
            second = temp;
        }
        return temp;
    }

    /**
     * 递归法
     *
     * @param n
     * @return
     */
    private static int fun1(int n) {
        if (n == 1 || n == 2) {
            return n;
        } else {
            return fun1(n - 1) + fun1(n - 2);
        }
    }
}
